package com.rzjm.api.netty.charger;

import cn.hutool.core.util.StrUtil;
import com.rzjm.api.entity.*;
import com.rzjm.api.service.*;
import com.rzjm.api.util.DateUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;

/**
 * @创建者：zhouwei
 * @创建时间：2021/5/24
 * @描述：
 */
@Component
public class MessageDecode {
    @Resource
    private ChargerService chargerService;
    @Resource
    private ChargerPortRecordService portRecordService;
    /*添加代码 begin*/
    private static MessageDecode messageDecode;
    @Resource
    protected RedisTemplate<String, Object> redisTemplate;

    @PostConstruct
    public void init(){
        messageDecode = this;
        messageDecode.chargerService = this.chargerService;
        messageDecode.portRecordService = this.portRecordService;
        messageDecode.redisTemplate = this.redisTemplate;
    }

    public static String onMessage(MessageModel model,String cellNum){
        String msg = "";
        if(model.getMsgType() == null){
            return "";
        }
        try{
            if(model.getMsgType() == 0){
                if(model.getOrder().equals("01")){//心跳
                    msg = model.getHeader() + model.getOrder() + model.getClientNum() + DateUtil.getSdfTimes() + model.getFooter();

                    String data = model.getData();
                    System.out.println("心跳数据：" + data);
                    if(data.contains("|")) {
                        String[] datas = data.split("\\|");
                        int index = 0;
                        for (String dataParam : datas){
                            if(dataParam.contains(",")) {
                                //MS01120000141,24017,75,00000001652362401153,783|0,77,30,,0,ME
                                //12000014
                                // 1,24017,75,00000001652362401153,783
                                // |
                                // 0,77,30,,0,ME
                                String[] dataArray = dataParam.split(",");
                                //状态,电压,电流,订单号,功率
                                //状态有：0待机，1充电，-1正在维修
                                // 订单号只有在充电状态有，其他为空即可
                                //两个插座就有两个数据，十个就会传十个
                                //携带订单号 在充电状态的 数据
                                if(Integer.parseInt(dataArray[0]) == 1){
                                    addPortRecord(model.getClientNum(),index + 1,dataArray,data,"01");
                                }else{//不带订单号的数据，要查询当前设备是否存在未结束的订单
                                    validateChargerOrder(model.getClientNum(),index + 1,dataArray,data,"01");
                                }
                            }
                            index++;
                        }
                    }

                } else if(model.getOrder().equals("02")){//初始化
                    msg = model.getHeader() + model.getOrder() + model.getClientNum()  + DateUtil.getSdfTimes() + model.getFooter();
                    //31,89860621290057129022,,1.0,
                    String data = model.getData();
                    //MS 02 22000030 31,89860621290057129022,,1.0,ME
                    //31,89860621290057129022,,1.0, 信号强度，ICCID，IMEI，版本
                    //信号强度,电话卡id，电话卡MEI,插座数量，程序版本
                    if(data.contains(",")){
                        String[] dataArray = data.split(",");
                        if(dataArray.length >= 3){
                            if(StrUtil.isNotEmpty(dataArray[1])){
                                updateDeviceSimCardNum(model.getClientNum(),dataArray);
                            }
                        }
                    }
                } else if(model.getOrder().equals("05")){//结束充电
                    //01表示收到
                    msg = model.getHeader()  + model.getOrder() + model.getClientNum() +  "01" + model.getFooter();
                    String data = model.getData();
                    if(data.contains(",")) {
                        //MS 05 12000014 00,00000001652362401153,,ME
                        //00,00000001652362401153,,
                        //端口号，订单号,故障信息（一个字节）
                        String[] dataArray = data.split(",");
                        overTask(model.getClientNum(), dataArray, data);
                    }
                } else if(model.getOrder().equals("10")){//开始充电
                    msg = model.getHeader()  + model.getOrder() + model.getClientNum() +  cellNum + model.getFooter();
                    String data = model.getData();
                    System.out.println("充电反馈数据：" + data);
                    if(data.contains(",")) {
                        //MS 10 22100001 01,1,00000001653574155250 ME
                        //端口号，订单号,故障信息（一个字节）
                        //MS 10 20220522 09,0,00000001660480532696 ME
                        String[] dataArray = data.split(",");
                        startCharger(model.getClientNum(), dataArray, data);
                    }
                }
                if(model.getOrder().equals("01")){
                    updateDeviceOnlineState(model.getClientNum(),1);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return msg;
    }

    public static Charger getChargerInfo(String deviceNum){
        Charger devices = messageDecode.chargerService.getChargerInfoBySn(deviceNum);
        if(devices == null){
            devices = new Charger();
            devices.setChargerSn(deviceNum);
            devices.setState(0);
            devices.setPointCount(10);
            devices.setCreateTime(new Date());
            int ret = messageDecode.chargerService.initCharger(devices);
        }
        return devices;
    }


    /**
     *  更改设备在线状态
     * @param deviceNum
     * @param onlineState
     */
    public static void updateDeviceOnlineState(String deviceNum,int onlineState){
        Charger charger = messageDecode.chargerService.getChargerInfoBySn(deviceNum);
        if(charger != null){
            charger.setOnlineState(onlineState);
            if(onlineState == 0){
                charger.setLastOfflineTime(new Date());
            }else{
                charger.setLastOnlineTime(new Date());
            }
            messageDecode.chargerService.updateById(charger);
        }
    }

    /**
     *  更改设备SIM卡编号
     * @param deviceNum
     * @param dataArray
     */
    public static void updateDeviceSimCardNum(String deviceNum,String[] dataArray){
        Charger charger = messageDecode.chargerService.getChargerInfoBySn(deviceNum);
        if(charger != null){
            ////信号强度,电话卡id，电话卡MEI,插座数量，程序版本
            charger.setSimCardNum(dataArray[1]);
            charger.setPointCount(Integer.parseInt(dataArray[3]));
            messageDecode.chargerService.updateById(charger);
        }
    }

    /**
     *  添加 心跳数据
     * @param deviceNum
     * @param dataArray
     */
    public static void addPortRecord(String deviceNum,int portIndex,String[] dataArray,String data,String orderNum){
        Charger charger = messageDecode.chargerService.getChargerInfoBySn(deviceNum);
        if(charger != null){
            if(charger.getIsFree() == null || charger.getIsFree() == 0){
                messageDecode.portRecordService.addRecord(charger,portIndex,dataArray,data,orderNum);
            }else{
                messageDecode.portRecordService.addRecordByFree(charger,portIndex,dataArray,data,orderNum);
            }
        }
    }


    /**
     *  检测 当前端口是否存在未结束的订单
     * @param deviceNum
     * @param dataArray
     */
    public static void validateChargerOrder(String deviceNum,int portIndex,String[] dataArray,String data,String orderNum){
        Charger charger = messageDecode.chargerService.getChargerInfoBySn(deviceNum);
        if(charger != null){
            messageDecode.portRecordService.validateChargerOrder(charger,portIndex,dataArray,data,orderNum);
        }
    }


    /**
     *  开始充电
     * @param deviceNum
     * @param dataArray
     */
    public static void startCharger(String deviceNum,String[] dataArray,String data){
        Charger charger = messageDecode.chargerService.getChargerInfoBySn(deviceNum);
        if(charger != null){
            messageDecode.portRecordService.startCharger(charger,dataArray,data);
        }
    }

    /**
     *  结束充电
     * @param deviceNum
     * @param dataArray
     */
    public static void overTask(String deviceNum,String[] dataArray,String data){
        Charger charger = messageDecode.chargerService.getChargerInfoBySn(deviceNum);
        if(charger != null){
            messageDecode.portRecordService.overTask(charger,dataArray,data);
        }
    }
}
